<template>
  <div class="shopping-card">
    <div class="card-title">
      {{ this.user.username }}的购物车
    </div>
    <div class="card-table">
      <a-table
        :columns="shoppingcolumns"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange
        }"
        :dataSource="dataSource"
        :pagination="false"
        :rowKey="record => record.id"
        bordered
      >
        //这里的slot表示把按钮放在子组件的那里，对应的就是tabel每个行子组件的num字段
        <div style="width: 150px" slot="num" slot-scope="text, record">
          <a-button :disabled="record.num <= 1" @click="spliceNum(record.id)">
            -
          </a-button>
          <a-input style="width: 40px" placeholder="1" v-model="record.num" />
          <a-button @click="addNum(record.id)">
            +
          </a-button>
        </div>
        <div
          style="width: 50px;cursor: pointer"
          slot="action"
          slot-scope="text, record"
        >
          <div @click="onDelete(record.id)">删除</div>
        </div>
      </a-table>
    </div>
    <div class="card-end">
      <div><span style="margin-left: 8px">
        <template v-if="hasSelected">
          {{ `已选择 ${selectedRowKeys.length} 项` }}
        </template>
      </span>总计：<span style="color: red;font-size: 20px">{{ calToltalPrice }}</span>元</div>
      <div><span>请选择收货地址：</span>
        <a-dropdown>
          <a-button>{{ addrBtnText }}</a-button>
          <a-menu slot="overlay">
            <a-menu-item v-for="addr in addresses" :key="addr" >
              <a @click="setAddrBtn(addr)">{{ addr }}</a>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </div>
      <div style="text-align: right"><a-button type="danger" @click="createOrder" :disabled="caldisablecreate">生成支付订单</a-button></div>
    </div>
  </div>
</template>
<script>
  import { findShoppingCartItemsbyuserid, addShoppingCart, decreaseShoppingCart, delShoppingCart, findUserAddress, createPayment } from '@/api/book'

  const shoppingcolumns = [
    {
      title: '商品名称',
      // key: 'bookname',
      dataIndex: 'bookname',
      align: 'center'
    },
    {
      title: '作者',
      // key: 'authors',
      dataIndex: 'authors',
      align: 'center'
    },
    {
      title: '商品单价',
      // key: 'price',
      dataIndex: 'price',
      align: 'center'
    },
    {
      title: '购买数量',
      // key: 'num',
      dataIndex: 'num',
      slots: { title: 'num' },
      scopedSlots: { customRender: 'num' },
      align: 'center'
    },
    {
      title: '小计',
      // key: '',
      dataIndex: 'singerNum',
      align: 'center'
    },
    {
      title: '添加时间',
      // key: 'createTime',
      dataIndex: 'createTime',
      align: 'center',
      customRender: (text, record, index) => {
        var tsmil = parseInt(text) * 1000
        var date = new Date(tsmil)
        var fmt = 'yyyy-MM-dd hh:mm:ss'
        var o = {
          'M+': date.getMonth() + 1, // 月份
          'd+': date.getDate(), // 日
          'h+': date.getHours(), // 小时
          'm+': date.getMinutes(), // 分
          's+': date.getSeconds(), // 秒
          'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
          'S': date.getMilliseconds() // 毫秒
        }

        if (/(y+)/.test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
        }

        for (var k in o) {
          if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(
              RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
          }
        }
        return fmt
      }
    },
    {
      title: '操作',
      // key: 'action',
      dataIndex: 'action',
      slots: { title: 'action' },
      scopedSlots: { customRender: 'action' },
      align: 'center'
    }
  ]
  export default {
    data () {
      return {
        user: {},
        dataSource: [],
        selectedRowKeys: [],
        totalPrice: 0,
        addresses: [],
        addrBtnText: '请选择收货地址',
        selectedAddr: '',
        shoppingcolumns
      }
    },
    methods: {
      setAddrBtn (text) {
        this.addrBtnText = text
        this.selectedAddr = text
      },
      onSelectChange (selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
        // console.log(this.selectedRowKeys)
      },
      loadUserAddresses () {
        setTimeout(() => {
          findUserAddress(this.user.id).then(res => {
            // console.log('**************收到返回值***************')
            // console.log(res)
            // console.log('**************收到返回值***************')
            // console.log(res.result)
            this.addresses = res.result
          }).catch(error => {
            if (error.response && error.response.status === 403) {
              this.$message.error('api请求方式错误')
            }
            if (error.response && error.response.status === 404) {
              this.$message.error('api未找到')
            }
            if (error.response && error.response.status === 500) {
              this.$message.error('服务器内部错误')
            }
          })
        }, 100)
      },
      loaddata () {
        // 重新加载购物车
        setTimeout(() => {
          findShoppingCartItemsbyuserid(this.user.id).then(res => {
            // console.log('**************收到返回值***************')
            // console.log(res)
            // console.log('**************收到返回值***************')
            // console.log(res.result)
            if (res.result.length === 0) {
              this.$message.error('购物车是空的哦！')
              return
            }
            var tmplst = res.result
            tmplst.forEach((value, key) => {
              var tmp = value.price * value.num
              var result = parseFloat(tmp)
              result = Math.round(tmp * 100) / 100
              tmp = result.toString()
              var posdecimal = tmp.indexOf('.')
              if (posdecimal < 0) {
                posdecimal = tmp.length
                tmp += '.'
              }
              // eslint-disable-next-line camelcase
              while (tmp.length <= posdecimal + 2) {
                tmp += '0'
              }
              value.singerNum = parseFloat(tmp)
              this.$store.commit('SET_COUNT', res.count)
            })
            this.dataSource = tmplst
          }).catch(error => {
            if (error.response && error.response.status === 403) {
              this.$message.error('api请求方式错误')
            }
            if (error.response && error.response.status === 404) {
              this.$message.error('api未找到')
            }
            if (error.response && error.response.status === 500) {
              this.$message.error('服务器内部错误')
            }
          })
        }, 100)
      },
      onDelete (id) {
        this.dataSource.forEach((val, index, arr) => {
          if (val.id === id) {
            var params = { 'userid': this.user.id, 'bookid': val.bookid }
            delShoppingCart(params).then(res => {
              this.$message.success(res.result)
              this.$store.commit('SET_COUNT', res.count)
            }).catch(error => {
              if (error.response && error.response.status === 403) {
                this.$message.error('api请求方式错误')
              }
              if (error.response && error.response.status === 404) {
                this.$message.error('api未找到')
              }
              if (error.response && error.response.status === 500) {
                this.$message.error('服务器内部错误')
              }
            })
          }
        })
        this.loaddata()
      },
      spliceNum (id) {
        this.dataSource.forEach((val, index, arr) => {
          if (val.id === id) {
            var params = { 'userid': this.user.id, 'bookid': val.bookid }
            decreaseShoppingCart(params).then(res => {
              this.$message.success(res.result)
            }).catch(error => {
              if (error.response && error.response.status === 403) {
                this.$message.error('api请求方式错误')
              }
              if (error.response && error.response.status === 404) {
                this.$message.error('api未找到')
              }
              if (error.response && error.response.status === 500) {
                this.$message.error('服务器内部错误')
              }
            })
          }
        })
        // 重新加载购物车
        this.loaddata()
      },
      addNum (id) {
        this.dataSource.forEach((val, index, arr) => {
          if (val.id === id) {
            var params = { 'userid': this.user.id, 'bookid': val.bookid }
            addShoppingCart(params).then(res => {
              this.$message.success(res.result)
            }).catch(error => {
              if (error.response && error.response.status === 403) {
                this.$message.error('api请求方式错误')
              }
              if (error.response && error.response.status === 404) {
                this.$message.error('api未找到')
              }
              if (error.response && error.response.status === 500) {
                this.$message.error('服务器内部错误')
              }
            })
          }
        })
        // 重新加载购物车
        this.loaddata()
      },
      createOrder () {
        if (this.selectedRowKeys.length === 0) {
          this.$message.error('未选择任何商品！')
          return
        }
        if (this.selectedAddr === '') {
          this.$message.error('未选择收货地址！')
          return
        }
        var selectedData = []
        this.selectedRowKeys.map((value, index, arr) => {
            this.dataSource.map((val1, index1, arr1) => {
              if (val1.id === value) {
                selectedData.push(val1)
              }
            })
          }
        )
        var params = { 'userid': this.user.id, 'order': selectedData, 'address': this.selectedAddr, 'totalPrice': this.totalPrice }
        createPayment(params).then(res => {
          if (res.success) {
            this.$message.success(res.result)
            this.$store.commit('SET_COUNT', res.count)
          } else {
            this.$message.error(res.result)
          }
        }).catch(error => {
          if (error.response && error.response.status === 403) {
            this.$message.error('api请求方式错误')
          }
          if (error.response && error.response.status === 404) {
            this.$message.error('api未找到')
          }
          if (error.response && error.response.status === 500) {
            this.$message.error('服务器内部错误')
          }
        })
        // this.loaddata()
        this.$router.push('/mybookstore/mybookStorepayment')
      },
      setTotalPrice (totalPrice) {
        this.totalPrice = totalPrice
      }
    },
    computed: {
      caldisablecreate () {
        if (this.selectedRowKeys.length > 0) {
          return false
        } else {
           return true
        }
      },
      hasSelected () {
        return this.selectedRowKeys.length > 0
      },
      calToltalPrice () {
        var tmp = 0.0
        if (this.selectedRowKeys.length > 0) {
          this.dataSource.map((val, index, arr) => {
            this.selectedRowKeys.map((selval, selinx, selarr) => {
              if (val.id === selval) {
                tmp = tmp + parseFloat(val.singerNum)
              }
            })
          })
        }
        var result = parseFloat(tmp)
        result = Math.round(tmp * 100) / 100
        tmp = result.toString()
        var posdecimal = tmp.indexOf('.')
        if (posdecimal < 0) {
          posdecimal = tmp.length
          tmp += '.'
        }
        // eslint-disable-next-line camelcase
        while (tmp.length <= posdecimal + 2) {
          tmp += '0'
        }
        this.setTotalPrice(tmp)
        return tmp
      }
    },
    mounted () {
      this.loaddata()
      this.loadUserAddresses()
    },
    created () {
      this.user = this.$store.getters.userInfo
    }
  }
</script>

<style scoped>
</style>
